package ext.tianma.bom.service.sourcingInterface;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import ext.com.iba.IBAUtil;
import ext.com.workflow.WorkflowUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.LWCUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.bom.util.WfUtil;
import ext.tianma.number.util.PartUtil;
import ext.tianma.workflow.SubmitBomReview;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.mail.EMailMessage;
import wt.org.GenericDirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.WTPrincipal;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionContext;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;

/**
 * sourcing相关service
 * 
 * @author lilin
 * @date 2019-01-21 17:13:35 +0800
 * 
 */
public class SourcingInterfaceService {

	private static final String RELEASE = "release";// 发布
	private static final String REJECT = "reject";// 驳回
	private static final String REJECTED = "REJECTED";// 已否决

	private static final String PART_SUPPLIER = "partSupplier";// 供应商
	private static final String PART_BUYER = "partBuyer";// 采购员
	private static final String OBSOLESCENCE = "OBSOLESCENCE";// 废弃状态
	private static final String rejectreason = "SourcingRejectReason";// IBA属性 // Sourcing驳回原因

	private static final String Updatereason = "SourcingUpdateReason";// IBA属性 // Sourcing二级物料BOM信息

	private static final String partSupplierWithSystemName = "partSupplierWithSystemName";// IBA属性
																							// 供应商partSupplierWithSystemName
	private static final String partBuyers = "partBuyers";// IBA属性 采购员
															// partBuyers
	private static final String SourcingWorkflow = "Sourcing驳回变更流程";// Sourcing驳回变更流程

	private static final String SourcingRejected = "Sourcing二级物料变更流程";// Sourcing驳回二级BOM信息流程

	/**
	 * 
	 * @param type         驳回或者发布
	 * @param rejectReason 驳回原因
	 * @param supplierInfo 供应商信息
	 * @param partNumber   物料编号
	 * @return
	 * @throws JSONException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String modifyAttrOrSendEmail(String type, String rejectReason, String supplierInfo, String buyer,
			String partNumber) throws JSONException {
		JSONObject obj = new JSONObject();
		String success = "success";
		String message = "成功！";
		try {
			WTPart part = PartUtil.getWTPartByNumber(partNumber);
			if (RELEASE.equals(type)) {// 发布
				Hashtable updateIBAValues = new Hashtable();
				updateIBAValues.put(PART_SUPPLIER, supplierInfo);
				updateIBAValues.put(PART_BUYER, buyer);
				part = (WTPart) IBAUtil.forceSetIBAValues(part, updateIBAValues);// 设置扩展属性
				sendEmail(part.getCreatorName(), partNumber + "物料已生效！", partNumber + "物料已生效！");
				message = "发布成功！";
			} else if (REJECT.equals(type)) {// 驳回
				part = (WTPart) WorkflowUtil.setLifeCycleState(part, OBSOLESCENCE);
				sendEmail(part.getCreatorName(), partNumber + "物料已失效！失效原因：" + rejectReason, partNumber + "物料已失效！");
				message = "驳回成功！";
			}
		} catch (WTException e) {
			success = "false";
			message = "接口错误！";
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			obj.put("success", success);
			obj.put("message", message);
		}
		System.out.println("obj===>>" + obj.toJSONString());
		return obj.toJSONString();
	}

	/**
	 * 发送邮件
	 * 
	 * @param userName
	 * @param content
	 * @param titleStr
	 * @return
	 */
	public static boolean sendEmail(String userName, String content, String titleStr) {
		try {
			WTUser user = getUserByName(userName);
			System.out.println("用户" + user);
			String emailAddr = user.getEMail();// 电子邮件
			System.out.println("emailAddr======" + emailAddr);
			// 邮件内容
			StringBuffer body = new StringBuffer();
			body.append(content);
			String[] emailSendTo = "".equals(emailAddr) || emailAddr == null ? null : emailAddr.split(";");// 2、why？
			EMailMessage email = EMailMessage.newEMailMessage();
			email.addEmailAddress(emailSendTo);
			// 邮件主题
			StringBuffer title = new StringBuffer();
			title.append(titleStr);
			email.setSubject(title.toString());
			email.setMultipartSubtype("text/html;charset=\"UTF8\"");
			email.addPart(body.toString(), "text/html;charset=\"UTF8\"");
			email.send(false);
			return true;
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}

	/***
	 * 根据用户名称获取user
	 * 
	 * @param name
	 * @return
	 * @throws WTException
	 */
	@SuppressWarnings("rawtypes")
	private static WTUser getUserByName(String name) throws WTException {
		WTUser user = null;
		QuerySpec qs = new QuerySpec(WTUser.class);
		SearchCondition sc = new SearchCondition(WTUser.class, WTUser.NAME, "=", name);
		qs.appendWhere(sc);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			user = (WTUser) qr.nextElement();
		}
		return user;
	}

	/**
	 * 处理Sourcing接口
	 * 
	 * @param array
	 */
	public static String handleSoucreInterface(JSONArray array) {
		System.out.println("=====================handleSoucreInterface:" + array.toString());
		JSONObject result = new JSONObject();
		String message = "";
		List<String> list = new ArrayList<String>();
		list.add("OBSOLESCENCE");
		list.add("RELEASED");
		list.add("UPDATE");
		try {
			for (int i = 0; i < array.length(); i++) {
				JSONObject ob = (JSONObject) array.get(i);
				String type = "";
				if (ob.has("type")) {
					// 料号
					String number = ob.getString("number");
					if (StringUtil.isNullOrEmpty(number)) {
						message += "编号不能为空;";
						continue;
					}
					WTPart part = GenericUtil.getPart(number, "", "");
					if (part == null) {
						message += "物料:" + number + "不存在;";
						continue;
					}
					type = ob.getString("type");
					if (StringUtil.isNullOrEmpty(type)) {
						message += "类型type不能为空;";
						continue;
					} else if (!list.contains(type)) {
						message += "类型type不正确;";
						continue;
					}
					// 废弃
					if (("UPDATE".equals(type)) || ("OBSOLESCENCE".equals(type))) {
						try {
							System.out.println("进入驳回变更流程============");
							// 1.发起变更流程
							// Map attributemap = new HashMap<String, String>();
							// 流程是否创建
							boolean flag = false;
							QueryResult qr = WfEngineHelper.service.getAssociatedProcesses(part, WfState.OPEN_RUNNING,
									null);
							WfProcess process = null;
							while (qr.hasMoreElements()) {
								process = (WfProcess) qr.nextElement();
								if (process.getTemplate().getName().equals(SourcingWorkflow)) {
									message = number + "在PLM端已存在正在运行的sourcing驳回流程";
									flag = true;
									break;
								}

							}
							if (!flag) {

								JSONObject msobject = new JSONObject(ob.getString("message"));
								String reason = "";
								if (msobject.has("reason")) {
									// souricing驳回原因 /废弃原因
									reason = msobject.getString("reason");
								}
								// 2.更新字段 sourcing驳回原因
								Hashtable<String, String> ibamap = new Hashtable<String, String>();
								if (!StringUtil.isNullOrEmpty(reason)) {
									// part = (WTPart) LWCUtil.setValue(part, rejectreason, reason);
									ibamap = addToHashtable(ibamap, rejectreason, reason);
									System.out.println("values===>>" + ibamap);
									IBAUtil.setSoftTypeIBAValues(part, ibamap);
									System.out.println("==设置驳回原因成功==");
									part = (WTPart) GenericUtil.checkout(part);
									part = (WTPart) GenericUtil.checkin(part);
									// part=(WTPart)PersistenceHelper.manager.save(part);
									// ibamap.put(rejectreason, reason);
									// part = (WTPart) IBAUtil.forceSetIBAValues(part, ibamap);
									System.out.println("==更新驳回原因成功==");
									System.out.println("===start Sourcing驳回变更流程=======");
									// WfUtil.startWorkflow(SourcingWorkflow, part, attributemap);
									SubmitBomReview.submitWorkflow(part, SourcingWorkflow, true);
									System.out.println("===end Sourcing驳回变更流程=======");
								}

								if (("OBSOLESCENCE".equals(type))) {
									boolean flag2 = sendEmail(part.getCreatorName(), number + "物料已失效！失效原因：" + reason,
											number + "物料已失效！");
									System.out.println("======已经发送邮件======" + flag2);
								}

								continue;
							}

						} catch (Exception e) {
							e.printStackTrace();
							System.out.println("========sourcing接口 废弃出错==========" + e);
						}

					} else if ("RELEASED".equals(type)) {
						// 生效
						try {

							boolean flag = false;
							QueryResult qr = WfEngineHelper.service.getAssociatedProcesses(part, WfState.OPEN_RUNNING,
									null);
							WfProcess process = null;
							while (qr.hasMoreElements()) {
								process = (WfProcess) qr.nextElement();
								if (process.getTemplate().getName().equals(SourcingWorkflow)) {
									message = number + "在PLM端已存在正在运行的sourcing驳回流程";
									flag = true;
									break;
								}

							}
							if (!flag) {

								JSONObject msobject = new JSONObject(ob.getString("message"));
								String reason = "";
								if (msobject.has("reason")) {
									// souricing驳回原因 /废弃原因
									reason = msobject.getString("reason");
								}
								// 2.更新字段 sourcing驳回原因
								Hashtable<String, String> ibamap = new Hashtable<String, String>();
								if (!StringUtil.isNullOrEmpty(reason)) {
									// part = (WTPart) LWCUtil.setValue(part, rejectreason, reason);
									ibamap = addToHashtable(ibamap, rejectreason, reason);
									System.out.println("values===>>" + ibamap);
									IBAUtil.setSoftTypeIBAValues(part, ibamap);
									System.out.println("==设置驳回原因成功==");
									//part = (WTPart) GenericUtil.checkout(part);
									//part = (WTPart) GenericUtil.checkin(part);
									// part=(WTPart)PersistenceHelper.manager.save(part);
									// ibamap.put(rejectreason, reason);
									// part = (WTPart) IBAUtil.forceSetIBAValues(part, ibamap);
									System.out.println("==更新驳回原因成功==");
									System.out.println("===start Sourcing驳回变更流程=======");
									// WfUtil.startWorkflow(SourcingWorkflow, part, attributemap);
									SubmitBomReview.submitWorkflow(part, SourcingWorkflow, true);
									System.out.println("===end Sourcing驳回变更流程=======");
								}

								continue;
							}

							// 2.发送邮件给创建者
							// sendEmail(part.getCreatorName(), number + "物料已生效！", number + "物料已生效！");
						} catch (Exception e) {
							e.printStackTrace();
							System.out.println("========sourcing接口  生效出错==========" + e);
						}
					}

				} else {
					message += "数据格式不正确，缺少type字段";
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if(message.contains("在PLM端已存在正在运行的sourcing驳回流程")||message.contains("数据格式不正确")) {
				result.put("status", "failed");
			}else {
				result.put("status", "success");
			}
			result.put("message", message);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result.toString();
	}

	/**
	 * 处理Sourcing接口 二级物料接口,用于修改信息
	 * 
	 * @param array
	 */
	public static String materialModificationSoucreInterface(JSONArray array) {
		System.out.println("SLC =二级物料接口=传递过来的数据==>:" + array.toString());
		JSONObject result = new JSONObject();
		String message = "";
		List<String> list = new ArrayList<String>();
		list.add("SUCCESS");
		list.add("UPDATE");
		try {
			for (int i = 0; i < array.length(); i++) {
				JSONObject ob = (JSONObject) array.get(i);
				String type = "";
				if (ob.has("type")) {
					// 料号
					String number = ob.getString("number");
					if (StringUtil.isNullOrEmpty(number)) {
						number = ob.getString("RFQProductNumber");
					}
					if (StringUtil.isNullOrEmpty(number)) {
						message += "编号不能为空;";
						continue;
					}
					WTPart part = GenericUtil.getPart(number, "", "");
					if (part == null) {
						message += "物料:" + number + "不存在;";
						continue;
					}
					type = ob.getString("type");
					if (StringUtil.isNullOrEmpty(type)) {
						message += "类型type不能为空;";
						continue;
					} else if (!list.contains(type)) {
						message += "类型type不正确;";
						continue;
					}
					// 二级物料接口,部件信息修改
					if ("UPDATE".equals(type)) {
						try {
							System.out.println("进入Sourcing驳回二级物料变更流程============");
							// 1.发起变更流程
							// Map attributemap = new HashMap<String, String>();
							// 流程是否创建
							boolean flag = false;
							QueryResult qr = WfEngineHelper.service.getAssociatedProcesses(part, WfState.OPEN_RUNNING,
									null);
							WfProcess process = null;
							while (qr.hasMoreElements()) {
								process = (WfProcess) qr.nextElement();
								if (process.getTemplate().getName().equals(SourcingRejected)) {
									message = number + "在PLM端已存在正在运行的Sourcing驳回二级物料变更流程";
									flag = true;
									break;
								}

							}
							if (!flag) {
								System.out.println("===start Sourcing驳回二级物料变更流程=======");
								// WfUtil.startWorkflow(SourcingWorkflow, part, attributemap);
								SubmitBomReview.submitWorkflow(part, SourcingRejected, true);
								System.out.println("===end Sourcing驳回二级物料变更流程=======");

								JSONObject msobject = new JSONObject(ob.getString("message"));
								String reason = "";
								if (msobject.has("reason")) {
									// souricing驳回二级物料原因
									reason = msobject.getString("reason");
								}
								// 2.更新字段 sourcing驳回原因
								Hashtable<String, String> ibamap = new Hashtable<String, String>();
								if (!StringUtil.isNullOrEmpty(reason)) {
									ibamap = addToHashtable(ibamap, Updatereason, reason);
									System.out.println("values===>>" + ibamap);
									IBAUtil.setSoftTypeIBAValues(part, ibamap);
									System.out.println("==设置驳回原因成功==");
									part = (WTPart) GenericUtil.checkout(part);
									GenericUtil.checkin(part);
									System.out.println("==更新驳回原因成功==");
								}

								if (("UPDATE".equals(type))) {
									boolean flag2 = sendEmail(part.getCreatorName(),
											number + "该物料BOM信息需要修改！修改原因：" + reason, number + "该物料BOM信息需要修改！");
									System.out.println("======已经发送邮件======" + flag2);
								}

								continue;
							}

						} catch (Exception e) {
							e.printStackTrace();
							System.out.println("========sourcing接口 废弃出错==========" + e);
						}

					} else if ("SUCCESS".equals(type)) {
						// 审批通过
						try {
							JSONObject msobject = new JSONObject(ob.getString("message"));
							String reason = "";
							if (msobject.has("reason")) {
								// souricing驳回二级物料原因
								reason = msobject.getString("reason");
							}
							Hashtable<String, String> ibamap = new Hashtable<String, String>();
							// 1.设置二级物料,审批通过
							if (!StringUtil.isNullOrEmpty(reason)) {
								// part = (WTPart) LWCUtil.setValue(part, rejectreason, reason);
								ibamap = addToHashtable(ibamap, Updatereason, reason);
								System.out.println("values===>>" + ibamap);
								IBAUtil.setSoftTypeIBAValues(part, ibamap);

								part = (WTPart) GenericUtil.checkout(part);
								part = (WTPart) GenericUtil.checkin(part);
								// 流程是否创建
								boolean flag = false;
								QueryResult qr = WfEngineHelper.service.getAssociatedProcesses(part,
										WfState.OPEN_RUNNING, null);
								WfProcess process = null;
								while (qr.hasMoreElements()) {
									process = (WfProcess) qr.nextElement();
									if (process.getTemplate().getName().equals(SourcingRejected)) {
										message = number + "在PLM端已存在正在运行的Sourcing驳回二级物料变更流程";
										flag = true;
										break;
									}

								}
								if (!flag) {
									System.out.println("===start Sourcing二级物料变更流程=======");
									// WfUtil.startWorkflow(SourcingWorkflow, part, attributemap);
									SubmitBomReview.submitWorkflow(part, SourcingRejected, true);
									System.out.println("===end Sourcing二级物料变更流程=======");
								}
								System.out.println("==更新二级物料BOM信息成功==");
								// 2.发送邮件给创建者
								sendEmail(part.getCreatorName(), number + "二级物料BOM,Sourcing审批通过！",
										number + "二级物料BOM已生效！");
							}

						} catch (Exception e) {
							e.printStackTrace();
							System.out.println("========sourcing接口  生效出错==========" + e);
						}
					}

				} else {
					message += "数据格式不正确，缺少type字段";
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			result.put("status", "success");
			result.put("message", message);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result.toString();
	}

	/**
	 * 实现Hashtable添加数据时不会出现空指针异常
	 * 
	 * @param hashtable
	 * @param key
	 * @param value
	 * @return
	 */
	private static Hashtable<String, String> addToHashtable(Hashtable<String, String> hashtable, String key,
			String value) {
		if (key == null && hashtable != null) {
			return hashtable;
		}

		if (value == null && hashtable != null) {
			return hashtable;
		}

		if (key == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (value == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (hashtable == null) {
			hashtable = new Hashtable<String, String>();
		}
		hashtable.put(key, value);

		return hashtable;
	}
}
